package cn.tedu.com.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RedisPoolListenerUtil implements ApplicationListener<ContextRefreshedEvent> {
    private static  final   Map<String, RedisTemplate<String,Object>> RT_UTIL=new ConcurrentHashMap<>();
    private  static final  Map<String, StringRedisTemplate> SRT_UTIL=new ConcurrentHashMap<>();
    public static final String REDIS_TEMPLATE_DB0="redisTemplate";
    public static final String REDIS_REMPLATE_DB1="rtOne";
    public static final String REDIS_STR_DB0="srtZero";
    public static final String REDIS_STR_DB1="srtOne";
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        ApplicationContext parent = applicationContext.getParent();
        if(Objects.isNull(parent)){
            Map<String, RedisTemplate> beansOfType = applicationContext.getBeansOfType(RedisTemplate.class);
            log.info("[RedisPoolListenerUtil] [onApplicationEvent]== rt beansOfType={}",beansOfType);
            beansOfType.forEach((k,v)->{
                if(!(v instanceof StringRedisTemplate)){
                    RT_UTIL.put(k,v);
                }

            });
            log.info("[RedisPoolListenerUtil] [onApplicationEvent]== rt RT_UTIL={}",RT_UTIL);
            Map<String, StringRedisTemplate> beansOfType1 = applicationContext.getBeansOfType(StringRedisTemplate.class);
            log.info("[RedisPoolListenerUtil] [onApplicationEvent]== srt beansOfType1={}",beansOfType1);
            beansOfType1.forEach((k,v)->{
                SRT_UTIL.put(k,v);
            });
            log.info("[RedisPoolListenerUtil] [onApplicationEvent]== rt SRT_UTIL={}",SRT_UTIL);

        }
    }

    public static RedisTemplate<String,Object> getRTDBByKey(String key){
        RedisTemplate<String, Object> redisTemplate = RT_UTIL.get(key);
        return  redisTemplate;
    }

    public static StringRedisTemplate getSRTDbByKey(String key){
        StringRedisTemplate stringRedisTemplate = SRT_UTIL.get(key);
        return stringRedisTemplate;
    }
}
